package com.zzzzzz.content.topic;

import org.bson.types.ObjectId;
import org.springframework.stereotype.Repository;

import com.google.code.morphia.query.Query;
import com.zzzzzz.core.dao.morphia.BaseDao;

@Repository("topicDao")
public class TopicDaoImpl extends BaseDao implements TopicDao {

	@Override
	public void add(Topic topic) {
		db.save(topic);
	}

	@Override
	public void editStatus(String userId, String topicId, Integer status) {
		Query<Topic> query = db.createQuery(Topic.class);
		query.filter("_id", ObjectId.massageToObjectId(topicId))
			.filter("userId", userId);
		db.update(query, db.createUpdateOperations(Topic.class).set("status", status));
	}

	@Override
	public void edit(Topic topic) {
		Query<Topic> query = db.createQuery(Topic.class);
		query.filter("_id", ObjectId.massageToObjectId(topic.getTopicId()))
			.filter("userId", topic.getUserId());
		db.update(query, db.createUpdateOperations(Topic.class)
				.set("title", topic.getTitle())
				.set("text", topic.getText())
				.set("categoryId", topic.getCategoryId())
				.set("tags", topic.getTags())
				.set("imgId", topic.getImgId())
				.set("imgSId", topic.getImgSId())
				.set("updDt", topic.getUpdDt())
		);
	}

	@Override
	public Topic findById(String topicId) throws NoSuchTopicException {
		Topic topic = db.find(Topic.class, "_id", ObjectId.massageToObjectId(topicId)).get();
		if(topic == null) {
			throw new NoSuchTopicException(topicId);
		}
		return topic;
	}
	
}
